<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    /**
     * 用户登录
     */
    public function login(Request $request)
    {
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        $user = User::where('username', $request->username)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'message' => '账号或密码错误'
            ], 401);
        }

        // 删除用户的所有旧token（可选，确保单点登录）
        // $user->tokens()->delete();
        
        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'data' => [
                'token' => $token
            ],
            'message' => '登录成功'
        ]);
    }

    /**
     * 用户退出
     */
    public function logout(Request $request)
    {
        // 删除当前访问令牌
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'message' => '退出成功'
        ]);
    }
}
